var express = require('express');
const multer = require('multer');
const documentarray = ['doc','docx','ppt','pptx','txt','xlms'];
const imagearray = ['png','gif','jpg','jpeg','bmp'];

const videoarray = ['rmvb','mpg','mpeg','mp4','wmv','avi','mov','qt','ram'];
const musicarray = ['mp3'];
const ziparray = ['zip','rar','iso'];
var router = express.Router();

var User = require('../models/users');
var Image = require('../models/imgs');
var Music = require('../models/music');
var Videos = require('../models/videos');
var Zip = require('../models/zip');
var Documents = require('../models/documents');
var Other = require('../models/other');


const storage = multer.diskStorage({

    destination: function (req, file, cb) {
        var filenameArr = file.originalname.split('.');
        var namelast = filenameArr[filenameArr.length-1];

        if(isInArray(documentarray,namelast))
        {
            cb(null, 'public/upload/document');
        }else if(isInArray(imagearray,namelast)){
            cb(null, 'public/upload/image');
        }
        else if(isInArray(videoarray,namelast)){
            cb(null, 'public/upload/video');
        }
        else if(isInArray(musicarray,namelast)){
            cb(null, 'public/upload/music');
        }
        else if(isInArray(ziparray,namelast)){
            cb(null, 'public/upload/zip');
        }
        else
            cb(null, 'public/upload/other');
    },
    filename: function (req, file, cb) {

        cb(null,file.originalname);//增加了文件的扩展名
    }
});
const upload = multer({storage: storage});

/* GET home page. */
router.get('/', function(req, res, next) {

  res.render('index', { title: '登录' });
});

router.get('/login_in_success', function(req, res, next) {
    res.render('login_in', { title: '网盘页面',username:req.query.username});
});

router.post('/logincheck', function (req, res) {
    var postData = {
        username: req.body.username,
        password: req.body.userpwd
    };

    User.findOne({
        username: postData.username,
        password: postData.password
    }, function (err, data) {
        if(err) throw err;
        if(data){
            res.send({'msgnum':0,'msg':'登录成功'});
        }else{
            res.send({'msgnum':-1,'msg':'账号密码不一致'});
        }
    } )
});

router.post('/register', function (req, res) {

    var postData = {
        username: req.body.registername,
        password: req.body.registerpwd
    };
    User.findOne({username: postData.username}, function (err, data) {

        if (data) {
            res.send({'msgnum':-1,'msg':'用户名已被注册'});
        } else {
            // 保存到数据库
            User.create(postData, function (err, data) {
                if (err) throw err;
                res.send({'msgnum':-0,'msg':'注册成功'});
            })
        }
    });
});

router.post('/upfile',upload.single('avatar'), function(req, res, next) {
  var fileobject = req.file;
    var filenameArr = fileobject.originalname.split('.');
    var namefirst = filenameArr[0];
    var namelast = filenameArr[filenameArr.length-1];
  var postData = {
      username:req.body.username,
      imgname:namefirst,
      imgtype:namelast,
      path:fileobject.destination,
      size: zjTokb(fileobject.size)+'KB',
      uploaddate:dateToString(new Date())
  }
    if(isInArray(documentarray,namelast))
    {
        Documents.create(postData, function (err, data) {
            if (err) throw err;
            res.send({'msgnum':-0,'msg':'上传成功'});
        })
    }else if(isInArray(imagearray,namelast)){
        Image.create(postData, function (err, data) {
            if (err) throw err;
            res.send({'msgnum':-0,'msg':'上传成功'});
        })
    }
    else if(isInArray(videoarray,namelast)){
        Videos.create(postData, function (err, data) {
            if (err) throw err;
            res.send({'msgnum':-0,'msg':'上传成功'});
        })
    }
    else if(isInArray(musicarray,namelast)){
        Music.create(postData, function (err, data) {
            if (err) throw err;
            res.send({'msgnum':-0,'msg':'上传成功'});
        })
    }
    else if(isInArray(ziparray,namelast)){
        Zip.create(postData, function (err, data) {
            if (err) throw err;
            res.send({'msgnum':-0,'msg':'上传成功'});
        })
    }
    else
    {
        Other.create(postData, function (err, data) {
            if (err) throw err;
            res.send({'msgnum':-0,'msg':'上传成功'});
        })
    }


});

router.post('/deletefile', function (req, res) {


});

router.post('/downfile', function (req, res) {


});

router.post('/openfile', function (req, res) {


});

router.post('/searchfile', function (req, res) {


});

function isInArray(arr,value){
    for(var i = 0; i < arr.length; i++){
        if(value.toLowerCase() === arr[i].toLowerCase()){
            return true;
        }
    }
    return false;
}
function dateToString(now){
    var year = now.getFullYear();
    var month =(now.getMonth() + 1).toString();
    var day = (now.getDate()).toString();
    var hour = (now.getHours()).toString();
    var minute = (now.getMinutes()).toString();
    var second = (now.getSeconds()).toString();
    if (month.length == 1) {
        month = "0" + month;
    }
    if (day.length == 1) {
        day = "0" + day;
    }
    if (hour.length == 1) {
        hour = "0" + hour;
    }
    if (minute.length == 1) {
        minute = "0" + minute;
    }
    if (second.length == 1) {
        second = "0" + second;
    }
    var dateTime = year + "-" + month + "-" + day +" "+ hour +":"+minute+":"+second;
    return dateTime;
}
function zjTokb(zj){
    return (zj/1024);
}
module.exports = router;
